package cn.hnu.qq.client.controller;

import java.util.Set;

import cn.hnu.qq.entity.User;
import cn.hnu.qq.entity.message.CrowdInfoMessage;
import cn.hnu.qq.entity.message.IpInfoMessage;
import cn.hnu.qq.entity.message.LogonSuccessMessage;
import cn.hnu.qq.entity.message.Message;
import cn.hnu.qq.entity.message.OnlineMessage;

/**
 * 处理监听服务器消息的线程的控制器
 * @author jared
 *
 */
public class ListenServerMessageThread extends CenterController implements Runnable{
	
	private static ListenServerMessageThread instance = null;
	
	private ListenServerMessageThread(){};
	
	public static synchronized ListenServerMessageThread getInstance(){
		if(instance == null){
			instance = new ListenServerMessageThread();
		}
		return instance;
	}

	public void run() {
		System.out.println("进入 ListenServerMessageThread run");
		while(true){
			try {
				Message message = (Message) getInput().readObject();
				
				/*
				 * 异步化对象输出方式 更好的方式应该采用fastJson
				 */
				getOutput();
				
				
				log.debug("获得服务器消息 ： "+message.getMessageType());
				
				
				switch(message.getMessageType()){
					case LOGON_SUCCESS:
						handleLogonSuccess((LogonSuccessMessage) message);
						break;
					case IP_INFO:
						handleIpInfo((IpInfoMessage)message);
						break;
					case CROWD_INFO:
						handleCrowdInfo((CrowdInfoMessage)message);
						break;
					case ONLINE:
						handleOnline((OnlineMessage) message);
						break;
					default:
							break;
				}
			} catch (Exception e) {
				System.err.println("读取对象失败");
				e.printStackTrace();
			}
		}
	}

	private void handleOnline(OnlineMessage message) {
		Set<User> users = getCurUser().getFriends();
		for(User u:users){
			if(u.getAcount().equals(message.getAccount())){
				u.setIp(message.getIpAddr());
				u.setUserClientPort(message.getPort());
				break;
			}
		}
	}

	private void handleCrowdInfo(CrowdInfoMessage message) {
		put(message.getMessageType(),message);
		messageArrived(message.getMessageType());
	}

	private void handleIpInfo(IpInfoMessage message) {
		put(message.getMessageType(),message);
		messageArrived(message.getMessageType());
	}

	private void handleLogonSuccess(LogonSuccessMessage message) {
		setCurUser(message.getUser());
		messageArrived(message.getMessageType());
	}
	
}
